package com.ajmd.onlineexam.baseUtil;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT操作工具类，用于 token操作
 * @author ajmd
 * @since 2023/3/12 22:30
 */
public class JWTUtils {
    private static final String SECERT="exam";

    /**
     * 生成 token
     * @param map
     * @return
     */
    public static String getToken(Map<String,String> map){
        JWTCreator.Builder builder = JWT.create();
        //设置payload
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        //设置过期时间
        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.HOUR,3);
        calendar.add(Calendar.DATE,7);
        Map<String,Object> header=new HashMap<>();
        header.put("alg","HS256");//alg字段指定了加密算法，这里使用HS256算法进行签名
        header.put("typ","JWT");//设置token类型
        return builder.withHeader(header)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECERT));
    }

    /**
     * 校验 token 是否合法
     *      DecodedJWT 可以用来获取用户信息
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        //如果不抛异常就说明验证通过
        DecodedJWT verify=null;
        try{
            verify = JWT.require(Algorithm.HMAC256(SECERT)).build().verify(token);
        }catch (SignatureVerificationException e){
            e.printStackTrace();
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
        }catch (TokenExpiredException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
        return verify;
    }
}
